//
//  SY_PaymentCountViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 2017/1/4.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_PaymentCountViewController.h"
#import "SY_PaymentDetailViewController.h"
#import "noReadModel.h"
#import "noReadListViewCell.h"

@interface SY_PaymentCountViewController ()<UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    EmptyStateView *noemptyView;//空状态
    EmptyStateView *allemptyView;//空状态
    
    UIButton *allSelectBtn;
    UIButton *sureBtn;
    BOOL flag;//是否全选
    int count;
    
    
}

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *listTabelView;
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSMutableArray *studentsArr;

@end

@implementation SY_PaymentCountViewController

- (void)loadView {
    [super loadView];
    
    self.navBar.nav_titleLabel.text = @"班级收费";
    self.view.backgroundColor = colorFromHex(@"#F5F8FA");
    
    self.type = 1;
    flag = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.detailModel) {
        
        [self creatView];
        [self requestData];
    }else {
        [self getReceiptInfo];
        
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Method

- (void)creatView {
    
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, 87)];
    [self.topView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.topView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 12, SCREENWIDTH - 130, 16)];
    titleLabel.text = self.detailModel.name;
    [titleLabel setFont:[UIFont systemFontOfSize:16]];
    [titleLabel setTextColor:colorFromHex(@"#3b3b3b")];
    
    [self.topView addSubview:titleLabel];
    
    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, titleLabel.bottom + 8, SCREENWIDTH - 130, 15)];
    contentLabel.text = self.detailModel.scontent;
    [contentLabel setFont:[UIFont systemFontOfSize:15]];
    [contentLabel setTextColor:colorFromHex(@"#979797")];
    
    [self.topView addSubview:contentLabel];
    
    float money = self.detailModel.money/100.0;
    UILabel *moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH - 115, 12, 100, 16)];
    moneyLabel.text = [NSString stringWithFormat:@"%.2f元",money];
    [moneyLabel setFont:[UIFont systemFontOfSize:16]];
    moneyLabel.textAlignment = NSTextAlignmentRight;
    [moneyLabel setTextColor:colorFromHex(@"#3b3b3b")];
    
    [self.topView addSubview:moneyLabel];
    
    UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, contentLabel.bottom + 11, SCREENWIDTH - 130, 13)];
    fromLabel.text = [NSString stringWithFormat:@"来源：%@",self.detailModel.classname];
    [fromLabel setFont:[UIFont systemFontOfSize:13]];
    [fromLabel setTextColor:colorFromHex(@"#3b3b3b")];
    
    [self.topView addSubview:fromLabel];
    
    UILabel *checkLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH - 100, fromLabel.y, 85, 13)];
    checkLabel.text = @"查看详情";
    [checkLabel setFont:[UIFont systemFontOfSize:13]];
    checkLabel.textAlignment = NSTextAlignmentRight;
    [checkLabel setTextColor:colorFromHex(@"#39adff")];
    
    [self.topView addSubview:checkLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(checkDetail)];
    [self.topView addGestureRecognizer:tap];
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, SCREENWIDTH, 10)];
    [view1 setBackgroundColor:colorFromHex(@"#F5F8FA")];
    [self.view addSubview:view1];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, self.topView.bottom+10, SCREENWIDTH, 58)];
    [backView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:backView];
    
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"未收费",@"已收费"]];
    [self.segment addTarget:self action:@selector(segmentChange:) forControlEvents:(UIControlEventValueChanged)];
    self.segment.size = CGSizeMake(250, 30);
    self.segment.center = CGPointMake(SCREENWIDTH/2,self.topView.bottom+10+16+15);
    self.segment.selectedSegmentIndex = 0;
    self.segment.tintColor = RGBCOLOR(57, 173, 255);
    
    UIFont *font = [UIFont systemFontOfSize:14.0f];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                           forKey:UITextAttributeFont];
    [self.segment setTitleTextAttributes:attributes
                                forState:UIControlStateNormal];
    
    NSString *title1 = [NSString stringWithFormat:@"未收费(%ld)",self.detailModel.znum - self.detailModel.paynum];
    NSString *title2 = [NSString stringWithFormat:@"已收费(%ld)",self.detailModel.paynum];
    //
    [self.segment setTitle:title1 forSegmentAtIndex:0];
    [self.segment setTitle:title2 forSegmentAtIndex:1];
    
    [self.view addSubview:self.segment];
    
    [self.view addSubview:self.listTabelView];
    [self.listTabelView setY:backView.bottom];
    
    
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH - SafeAreaTopHeight - 20-38-10-27-12, SCREENWIDTH, 200)];
    [self.bottomView setBackgroundColor:[UIColor whiteColor]];
    
    if (self.detailModel.state == 1) {
        [self.view addSubview:self.bottomView];
    }
    
    
    allSelectBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    allSelectBtn.frame=CGRectMake([UIScreen mainScreen].bounds.size.width-64,12, 52, 23);
    
    [allSelectBtn setImage:[UIImage imageWithOriginalName:@"all_choose_press_"] forState:UIControlStateNormal];
    
    [allSelectBtn addTarget:self action:@selector(selectTouchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:allSelectBtn];
    
    
    sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(12, allSelectBtn.bottom+24, [UIScreen mainScreen].bounds.size.width-24, 38);
    sureBtn.layer.cornerRadius=5;
    [sureBtn setTitle:@"再次通知" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(secondNoticeAction:) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn setBackgroundColor:RGBACOLOR(0, 180, 255, 1)];
    [self.bottomView addSubview:sureBtn];
    
    noemptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake(0, (SCREENHEIGH-110)/2, SCREENWIDTH, 110) andBackImage:@"participationlist_empty" andBottomStr:@"全体成员未交费"];
    [self.view addSubview:noemptyView];
    
    allemptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake(0, (SCREENHEIGH-110)/2, SCREENWIDTH, 110) andBackImage:@"participationlist_empty" andBottomStr:@"全体成员已交费"];
    [self.view addSubview:allemptyView];
    
}

- (void)segmentChange:(UISegmentedControl *)segment {
    
    self.type = segment.selectedSegmentIndex == 0 ? 1 : 2;
    
    flag = YES;
    [allSelectBtn setImage:[UIImage imageWithOriginalName:@"all_choose_press_"] forState:UIControlStateNormal];
    
    [self requestData];
}

#pragma mark - Request

- (void)getReceiptInfo {
    
    NSMutableDictionary *parmaDic = [[NSMutableDictionary alloc]init];
    
    [parmaDic setObject:@"api_receiptinfo_teacher" forKey:@"method"];
    [parmaDic setObject:USERID forKey:@"userid"];
    [parmaDic setObject:self.payId forKey:@"receiptid"];
    [parmaDic setObject:self.classId forKey:@"classid"];
    
    [Utils get:nil parameters:parmaDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *dataArr = [jsonObject objectForKey:@"re_data"];
        
        if (dataArr != nil && dataArr.count > 0) {
            self.detailModel = [SY_Par_PaymentModel mj_objectWithKeyValues:[dataArr objectAtIndex:0]];
            
            [self creatView];
            [self requestData];
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)requestData {
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    [paramDic setObject:USERID forKey:@"userid"];
    [paramDic setObject:[NSString stringWithFormat:@"%ld",self.type] forKey:@"type"];
    [paramDic setObject:@"api_receiptinfo_toteacher" forKey:@"method"];
    [paramDic setObject:[NSString stringWithFormat:@"%ld",self.detailModel.classid] forKey:@"classid"];
    [paramDic setObject:[NSString stringWithFormat:@"%ld",self.detailModel.receiptid] forKey:@"receiptid"];
    
    [Utils get:nil parameters:paramDic success:^(NSInteger recode, id jsonObject) {
        
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if ([arr count] > 0) {
            
            self.bottomView.hidden = self.type == 1?NO:YES;
            self.view.backgroundColor=RGBCOLOR(240,239,245);
            self.listTabelView.hidden = NO;
            
            [self.view setBackgroundColor:colorFromHex(@"#F5F8FA")];
            [self->noemptyView hideEmptyImage];
            [self->allemptyView hideEmptyImage];
            
            self.studentsArr = [[NSMutableArray alloc]init];
            
            for (NSDictionary *dic in arr) {
                
                noReadModel *model = [noReadModel mj_objectWithKeyValues:dic];
                model.check=YES;
                [self.studentsArr addObject:model];
                
            }
            [self.listTabelView.mj_header endRefreshing];
            
            if (self.detailModel.state == 1) {
                if (44*self.studentsArr.count > SCREENHEIGH - SafeAreaTopHeight - 288) {
                    [self.listTabelView setHeight:SCREENHEIGH - SafeAreaTopHeight - 288];
                    self.listTabelView.scrollEnabled = YES;
                }else {
                    [self.listTabelView setHeight:44*self.studentsArr.count];
                    self.listTabelView.scrollEnabled = NO;
                }
            }else {
                if (44*self.studentsArr.count > SCREENHEIGH - SafeAreaTopHeight - 155) {
                    [self.listTabelView setHeight:SCREENHEIGH - SafeAreaTopHeight - 155];
                    self.listTabelView.scrollEnabled = YES;
                }else {
                    [self.listTabelView setHeight:44*self.studentsArr.count];
                    self.listTabelView.scrollEnabled = NO;
                }
            }
            
            
            [self.listTabelView reloadData];
            
            //[self->line setY:self.listTabelView.height-0.5];
            
        }else {
            
            self.bottomView.hidden = YES;
            [self.view setBackgroundColor:colorFromHex(@"#ffffff")];
            self.listTabelView.hidden = YES;
            if (self.type == 1) {//未收费
                
                [self->allemptyView showEmptyImage];
                [self->noemptyView hideEmptyImage];
                
            }else {//已收费
                
                [self->allemptyView hideEmptyImage];
                [self->noemptyView showEmptyImage];
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

#pragma mark - Action

- (void)checkDetail {
    
    SY_PaymentDetailViewController *detailVC = [[SY_PaymentDetailViewController alloc]init];
    detailVC.detailModel = self.detailModel;
    detailVC.navBar.nav_titleLabel.text = @"收费详情";
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(void)dianjiTouchAction:(UIButton *)sender
{
    
    noReadListViewCell *cell=[self.listTabelView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag-100 inSection:0]];//获取当前点击cell
    int row=(int)(sender.tag-100);
    noReadModel *model=[self.studentsArr objectAtIndex:row];
    model.check=!model.check;
    if (!model.check) {
        count--;
        [self.studentsArr replaceObjectAtIndex:row withObject:model];
        [allSelectBtn setImage:[UIImage imageWithOriginalName:@"all_choose_"] forState:UIControlStateNormal];
        flag=NO;
        
        
    }else
    {
        count++;
        [self.studentsArr replaceObjectAtIndex:row withObject:model];
        if (count==[self.studentsArr count]) {
            [allSelectBtn setImage:[UIImage imageWithOriginalName:@"all_choose_press_"] forState:UIControlStateNormal];
            flag=YES;
        }
    }
    if (model.check) {
        cell.selectImage.image=[UIImage imageWithOriginalName:@"homeworks_allchoose_press_"];
    }else
    {
        cell.selectImage.image=[UIImage imageWithOriginalName:@"homeworks_allchoose_nor_"];
    }
    
}

-(void)selectTouchAction:(UIButton *)sender
{
    //flag=yes 全选；=no 全部取消
    //全选
    flag = !flag;
    if (flag==YES) {
        [allSelectBtn setImage:[UIImage imageWithOriginalName:@"all_choose_press_"] forState:UIControlStateNormal];
        count=(int)self.studentsArr.count;
        if (self.studentsArr.count>0) {
            for ( int i=0;i<self.studentsArr.count;i++) {
                noReadModel *model=[self.studentsArr objectAtIndex:i];
                model.check=YES;
                [self.studentsArr replaceObjectAtIndex:i withObject:model];
            }
        }
        
    }else
    {
        [allSelectBtn setImage:[UIImage imageNamed:@"all_choose_"] forState:UIControlStateNormal];
        count=0;
        for ( int i=0;i<self.studentsArr.count;i++) {
            noReadModel *model=[self.studentsArr objectAtIndex:i];
            model.check=NO;
            [self.studentsArr replaceObjectAtIndex:i withObject:model];
        }
    }
    [self.listTabelView reloadData];
    
}

-(void)secondNoticeAction:(UIButton *)sender
{
    //sureBtn.enabled = NO;
    NSMutableArray *XIDArray=[NSMutableArray array];
    
    for (int i=0; i<[self.studentsArr count]; i++) {
        noReadModel *model=[self.studentsArr objectAtIndex:i];
        if (model.check) {
            [XIDArray addObject:[NSString stringWithFormat:@"%ld",(long)model.userid]];
        }
    }
    
    if (XIDArray.count==0) {
        [Utils alertViewWithMessage:@"请选择学生！"];
        sureBtn.enabled = YES;
        return;
    }
    
    NSString *gouxuanStr=[XIDArray componentsJoinedByString:@","];
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_receipt_remindagain" forKey:@"method"];
    [dict setObject:gouxuanStr forKey:@"students"];
    [dict setObject:[NSString stringWithFormat:@"%ld",self.detailModel.receiptid] forKey:@"receiptid"];
    [dict setObject:[NSString stringWithFormat:@"%ld",self.detailModel.classid] forKey:@"classid"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary *remindagaindic = (NSDictionary *)resposeJson;
        
        self->sureBtn.enabled = YES;
        
        [Utils alertViewWithMessage:[remindagaindic objectForKey:@"re_info"]];
        
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
}

#pragma mark - TableViewData && TableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.studentsArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIndentifier=@"cell";
    
    noReadListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if (cell==nil) {
        cell = [[noReadListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    //cell.selectionStyle=UITableViewCellSelectionStyleNone;//取消选择状态
    //cell.delegate=self;
    cell.index=indexPath;
    
    if (self.type == 1) {
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        noReadModel *model=[self.studentsArr objectAtIndex:indexPath.row];
        NSString *  nameStr=model.username;
        
        cell.nameLabel.text=nameStr;
        if (![model.logo hasPrefix:@"http"]) {
            NSString * logo = [REQUESTIMAGEURL stringByAppendingString:model.logo];
            [cell.headView.headImage sd_setImageWithURL:[NSURL URLWithString:logo]];
        }
        cell.headView.flag=NO;
        if (nameStr.length > 2) {
            nameStr = [nameStr substringFromIndex:nameStr.length-2];
        }
        cell.headView.namelabel.font=[UIFont systemFontOfSize:12];
        cell.headView.namelabel.text=nameStr;
        
        if (self.detailModel.state == 1) {
            cell.selectBtn.tag=indexPath.row+100;
            cell.selectBtn.userInteractionEnabled=YES;
            cell.selectImage.hidden=NO;
            cell.selectBtn.enabled=YES;
            [cell.selectBtn addTarget:self action:@selector(dianjiTouchAction:) forControlEvents:UIControlEventTouchUpInside];
            
            if (model.check) {
                cell.selectImage.image=[UIImage imageNamed:@"homeworks_allchoose_press_"];
            }else {
                cell.selectImage.image=[UIImage imageWithOriginalName:@"homeworks_allchoose_nor_"];
            }
            
        }else {
            cell.selectImage.hidden=YES;
            cell.selectBtn.enabled=NO;
        }
        
        cell.line.hidden=NO;
        cell.lLine.hidden=YES;
        
        if (indexPath.row==([self.studentsArr count]-1)) {
            cell.line.hidden=YES;
            cell.lLine.hidden=NO;
        }
        
    }else{
        
        noReadModel *model=[self.studentsArr objectAtIndex:indexPath.row];
        NSString *  nameStr=model.username;
        
        cell.nameLabel.text=nameStr;
        
        if (![model.logo hasPrefix:@"http"]) {
            NSString * logo = [REQUESTIMAGEURL stringByAppendingString:model.logo];
            [cell.headView.headImage sd_setImageWithURL:[NSURL URLWithString:logo]];
        }
        
        cell.headView.flag=NO;
        if (nameStr.length > 2) {
            nameStr = [nameStr substringFromIndex:nameStr.length-2];
        }
        cell.headView.namelabel.font=[UIFont systemFontOfSize:12];
        cell.headView.namelabel.text=nameStr;
        cell.selectImage.hidden=YES;
        cell.selectBtn.enabled=NO;
        
        cell.line.hidden=NO;
        cell.lLine.hidden=YES;
        
        if (indexPath.row==([self.studentsArr count]-1)) {
            cell.line.hidden=YES;
            cell.lLine.hidden=NO;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.type == 2) {
        
        noReadModel *model=[self.studentsArr objectAtIndex:indexPath.row];
        
        SY_PaymentDetailViewController *detailVC = [[SY_PaymentDetailViewController alloc]init];
        detailVC.payid = [NSString stringWithFormat:@"%ld",model.payid];
        detailVC.title = @"收费详情";
        detailVC.isShowStudentName = 1;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


#pragma mark - Get & Set

- (UITableView *)listTabelView {
    
    if (_listTabelView == nil) {
        
        _listTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, 0) style:UITableViewStylePlain];
        _listTabelView.delegate = self;
        _listTabelView.dataSource = self;
        _listTabelView.rowHeight = 44;
        _listTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _listTabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            
//            [self requestData];
//        }];
//        _listTabelView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//            
//            [self requestMoreData];
//            
//        }];
        
    }
    
    return _listTabelView;
}


@end
